package com.github.fancyideas.security;

import com.github.fancyideas.security.module.entity.UserEntity;
import com.github.fancyideas.security.module.view.UserRoleView;
import com.github.fancyideas.security.repository.UserRepo;
import com.github.fancyideas.security.repository.UserRoleViewRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Set;

@Service
public class SecurityUserDetailService implements UserDetailsService {


    @Autowired
    private UserRepo userRepository;

    @Autowired
    private UserRoleViewRepo userRoleViewRepo;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        UserEntity user = userRepository.findUserByUsername(username);
        UserRoleView userRoleView = userRoleViewRepo.findViewUserRoleByUserId(user.getUserId());

        Set<SimpleGrantedAuthority> grantedAuthorities = new HashSet<>();
        String roleName = userRoleView.getRoleName();
        grantedAuthorities.add(new SimpleGrantedAuthority(roleName));
        return new User(
                user.getUsername(),
                user.getPassword(),
                grantedAuthorities);
    }
}
